import os
import subprocess

def block_network_for_executables(folder_path):
    # 检查文件夹是否存在
    if not os.path.exists(folder_path):
        print("文件夹不存在，请重新输入。")
        return

    # 改变当前工作目录到指定的文件夹
    if os.getcwd() != folder_path:
        os.chdir(folder_path)

    # 遍历文件夹及其子文件夹中的所有 .exe 文件
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith(".exe"):
                exe_path = os.path.join(root, file)
                # 为每个 .exe 文件创建阻止入站和出站的规则
                for direction in ["in", "out"]:
                    rule_name = f"Blocked {exe_path} via script"
                    command = [
                        "netsh",
                        "advfirewall",
                        "firewall",
                        "add",
                        "rule",
                        f"name={rule_name}",
                        f"dir={direction}",
                        f"program={exe_path}",
                        "action=block",
                        "enable=yes"
                    ]
                    # 执行命令
                    subprocess.run(command)
                    print(f"创建禁止 {direction} 规则【{exe_path}】")

    print(f"搞定了，{folder_path} 中所有 exe 文件的禁止入站、出站规则都已成功创建！")

# 主程序
while True:
    folder_path = input("请输入文件夹路径（退出请输入'exit'）：")
    if folder_path.lower() == 'exit':
        break
    block_network_for_executables(folder_path)
